/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2018 All Rights Reserved.
 */
package com.antcloud.demo.antscheduler.nine1nine;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;

import com.alipay.antschedulerclient.common.ClientCommonResult;
import com.alipay.antschedulerclient.handler.IClusterJobExecuteHandler;
import com.alipay.antschedulerclient.model.ClusterJobExecuteContext;
import com.alipay.antschedulerclient.model.chunk.ShardingChunkData;
import com.alipay.sofa.pay.facade.PayService;
import com.alipay.sofa.pay.facade.model.PayOrder;
import com.antcloud.demo.antscheduler.dal.daointerface.BillItemDAO;
import com.antcloud.demo.antscheduler.dal.dataobject.BillItemDO;
import com.google.common.collect.Maps;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

/**
 *
 * @author qian.lqlq
 * @version $Id: PaymentBalanceExecutor.java, v 0.1 2018年09月05日 18:42 qian.lqlq Exp $
 */
public class PaymentBalanceExecutor implements IClusterJobExecuteHandler {

    @Autowired
    private PayService  payService;

    @Autowired
    private BillItemDAO billItemDAO;

    @Override
    public ClientCommonResult handle(ClusterJobExecuteContext context) {
        ShardingChunkData shardingChunkData = (ShardingChunkData) context.getChunk();
        BillItemTypeEnum type = BillItemTypeEnum.valueOf(shardingChunkData.getShardingRule());
        List<PayOrder> orders = payService.listPayOrders(null, null);
        Map<String, BillItem> billItemMap = Maps.newHashMap();
        for (PayOrder payOrder : orders) {
            String userId = type == BillItemTypeEnum.EXPAND ? payOrder.getBuyerId()
                : payOrder.getSellerId();
            long ammount = payOrder.getPayAmount();
            if (!billItemMap.containsKey(userId)) {
                billItemMap.put(userId, new BillItem(userId, BillItemTypeEnum.EXPAND));
            }
            billItemMap.get(userId).addAmount(ammount);
        }
        billItemDAO.deleteByType(type.name());
        if (!CollectionUtils.isEmpty(billItemMap)) {
            for (BillItem billItem : billItemMap.values()) {
                BillItemDO billItemDO = new BillItemDO();
                BeanUtils.copyProperties(billItem, billItemDO, new String[] { "type" });
                billItemDO.setType(type.name());
                billItemDAO.insert(billItemDO);
            }
        }
        return ClientCommonResult.buildSuccessResult();

    }

    @Override
    public String getName() {
        return "paymentBalanceExecutor";
    }

    @Override
    public ThreadPoolExecutor getThreadPool() {
        return null;
    }
}